package com.augurit.gzcgwsp.jzfqwczzxn.web;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.jbpm.api.ProcessEngine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.Struts2Utils;

import com.augurit.common.base.action.BaseAction;
import com.augurit.common.base.action.CrudActionSupport;
import com.augurit.common.syscode.service.ISysCodeService;
import com.augurit.common.syscode.web.form.SysCodeForm;
import com.augurit.common.system.util.WebContextUtils;
import com.augurit.common.system.web.auth.form.LoginUserForm;
import com.augurit.common.util.ChineseChar;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.gzcgwsp.commonex.util.lang.DateUtilsEX;
import com.augurit.gzcgwsp.jzfqwczzpfsn.entity.ReplyTemplate;
import com.augurit.gzcgwsp.jzfqwczzpfsn.service.IYwYnJzfqwczzPfsnService;
import com.augurit.gzcgwsp.jzfqwczzxn.entity.YwYnJzfqwczzXn;
import com.augurit.gzcgwsp.jzfqwczzxn.service.IYwYnJzfqwczzXnQxService;
import com.augurit.gzcgwsp.jzfqwczzxn.service.IYwYnJzfqwczzXnService;
import com.augurit.gzcgwsp.jzfqwczzxn.web.form.YwYnJzfqwczzXnForm;
import com.augurit.gzcgwsp.printDoc.service.IYwPrintDocService;
import com.augurit.gzcgwsp.printDoc.web.form.YwPrintDocForm;
import com.augurit.gzcgwsp.wfex.app.doc.IOaDocCodeServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfBusTemplateServiceEX;
import com.augurit.gzcgwsp.wfex.bi.service.IWfTemplateAttachmentRefServiceEX;
import com.augurit.gzcgwsp.wfex.bi.web.form.WfTemplateAttachmentRefFormEX;
import com.augurit.gzcgwsp.wfex.common.service.IWfServiceEX;
import com.augurit.gzcgwsp.wfex.common.util.WfUtilsEX;
import com.augurit.gzcgwsp.ywcmn.convert.YwComSjcllistConvertor;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjclService;
import com.augurit.gzcgwsp.ywcmn.service.IYwComSjcllistOtherService;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjclForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistForm;
import com.augurit.gzcgwsp.ywcmn.web.form.YwComSjcllistOtherForm;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.web.form.WfBusInstanceTaskForm;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.common.constant.WfConstant;
import com.augurit.wf.common.form.WfBusSaveResult;
import com.augurit.wf.common.service.IWfBusClientService;
import com.augurit.wf.common.service.IWfService;
import com.augurit.wf.common.util.WfUtils;
import com.augurit.wf.common.web.WfBusClientAction;

@SuppressWarnings("serial")
@Results({
	@Result(name = CrudActionSupport.RELOAD, location = "yw-yn-jzfqwczz-xn-qx.action", type = "redirect"),
	@Result(name = CrudActionSupport.SUCCESS, location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzXn/qx/YwYnJzfqwczzXnQx.jsp"),
	@Result(name = CrudActionSupport.INPUT, location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzXn/qx/YwYnJzfqwczzXnQx-input.jsp"),
	@Result(name = WfConstant.PRINT, location = WfConstant.PRINT_JSP),
    @Result(name = WfConstant.PRINT_DIR, location = WfConstant.PRINT_DIR_JSP),
    @Result(name = WfConstant.MAKE_DOCUMENT, location = "/gzcgwsp/wfex/client/common/qumake-noline-document.jsp"),
    @Result(name = "preViewFh", location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzXn/preViewFh.jsp"),
    @Result(name = "preViewCzz", location = "/gzcgwsp/jzfqwczz/YwYnJzfqwczzXn/preViewCzz.jsp")
})
public class YwYnJzfqwczzXnQxAction extends WfBusClientAction<YwYnJzfqwczzXnForm>{
	private static final Logger log=Logger.getLogger(YwYnJzfqwczzXnQxAction.class);
	@Autowired
    private IWfServiceEX wfServiceEX;
	@Autowired
	private IYwComSjcllistOtherService ywComSjcllistOtherService;
	@Autowired
	private IYwYnJzfqwczzXnQxService ywYnJzfqwczzXnQxService;
	@Autowired
	private IYwYnJzfqwczzPfsnService ywYnJzfqwczzPfsnService;
    @Autowired
    private IWfBusTemplateService wfBusTemplateService;
    @Autowired
    private ISysCodeService syscodeService;
    @Autowired
    private IYwPrintDocService ywPrintDocService;
    @Autowired
    private IWfService wfService;
    @Autowired
    private IWfBusTemplateServiceEX wfBusTemplateServiceEX;
    @Autowired
    private IWfTemplateAttachmentRefServiceEX wfTemplateAttachmentRefServiceEX;
    @Autowired
    private IOaDocCodeServiceEX oaDocCodeServiceEX;
    @Autowired
	private IYwYnJzfqwczzXnService ywYnJzfqwczzXnService;
    @Autowired
    private IYwComSjclService ywComSjclService;
    @Autowired
    private ProcessEngine processEngine;
	private YwYnJzfqwczzXnForm form;
	private Long id;
	private Long[] checkedIds;
	private Page<YwYnJzfqwczzXnForm> page = new Page<YwYnJzfqwczzXnForm>(10);

    /**
     * 保存业务并关联流程实例
     */
    public String wfBusSave() {
    	try{
    		LoginUserForm user = (LoginUserForm)getSession().getAttribute(WebContextUtils.SES_LOGIN_USER);
    	    String orgName = user.getOrg().getOrgName();
    		if(StringUtils.isNotBlank(orgName)){//把所属区保存到WfBusInstance表的busMemo2字段里面
    			form.setSsq(orgName.substring(0,3));	
    		}
	        WfBusInstanceTaskForm task = this.wfBusSave((IWfBusClientService)ywYnJzfqwczzXnQxService, form, YwYnJzfqwczzXn.class.getSimpleName());
	        String isYsl = super.getParameter("isYsl");
	        if (StringUtils.isNotBlank(isYsl) && "1".equals(isYsl)) {
	        	String executionId =  processEngine.getHistoryService().createHistoryTaskQuery().taskId(task.getTaskInstDbid().toString()).uniqueResult().getExecutionId();
	            processEngine.getExecutionService().jumpToActivity(executionId, "cksa");
	            form.setYsl(null);
	            ywYnJzfqwczzXnQxService.changeYslState(form.getId(), null,"");
	        }
	        WfUtils.renderWfBusSaveJson(task, form);
    	}catch (Exception e) {
      		WfUtils.renderWfFailtureJson("请检查输入内容长度是否过大!");
   		}
        return null;
    }
    
    public String wfBusYslTuih() throws Exception {
    	try {
    		ywYnJzfqwczzXnQxService.wfBusYslTuih(form, this.getLoginUser());
			WfBusSaveResult result = new WfBusSaveResult(true, null);
			result.setTask(new WfBusInstanceTaskForm());
			Struts2Utils.renderJson(result);
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    /**
     * 出证
     */
    public String printcz() throws Exception {
    	String taskId=getRequest().getParameter("taskInstDbid");
    	String activName="";
    	if(StringUtils.isNotBlank(taskId)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskId), this.getLoginUserName());
			activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
    	if(form.getId() != null && form.getId() > 0){
    		List<YwPrintDocForm> ywPrintDocFormList = ywPrintDocService.get(form.getTemplateCode(), form.getFileCode(), form.getId());
        	if(ywPrintDocFormList!=null && ywPrintDocFormList.size()>0){
    			return WfConstant.PRINT_DIR;
    		}
    	}
    	
    	  try{//构造数据,放入书签中
              Map<String, String> variables=WfUtilsEX.buildMap(form,"yyyy年MM月dd日");
              if("sjtzs".equals(form.getFileCode())||("qusjtzs").equals(form.getFileCode())&& "cksa".equals(activName)){
            		String acceptNo=ywPrintDocService.updateQuAcceptNo(getTemplateCode(), String.valueOf(id),form.getAcceptNo());
            		if(StringUtils.isNotBlank(acceptNo)){
               		variables.put("acceptNo", acceptNo);
               		variables.put("serialNo", acceptNo);
               		variables.put("acceptNo1", acceptNo);
               		variables.put("serialNo1", acceptNo);
               		variables.put("acceptNo2", acceptNo);
               		variables.put("acceptNo3", acceptNo);
               		variables.put("serialNo2", acceptNo);
               	}
               }
              variables.put("ysgs1", form.getYsgs());
               //获取收件材料数据放到map中
              List<YwComSjcllistForm> sjlist=ywYnJzfqwczzXnService.getSjcls(form);
              YwComSjclForm fkForm = new YwComSjclForm();
              YwComSjcllistForm sjclform=new YwComSjcllistForm();
              sjclform.setAjid(form.getId());
              sjclform.setQyid(form.getQyid());
              sjclform.setBelongType(form.getGclb());
              sjclform.setTplcode(form.getTemplateCode());
              fkForm.setFkid(form.getQyid());
              fkForm.setAjid(form.getId());
              fkForm.setTplcode(getTemplateCode());
              List<YwComSjclForm> sjclTpl = ywComSjclService.getList(fkForm);
              List<YwComSjcllistOtherForm> sjclList = ywComSjcllistOtherService.getList(sjclform);
              List<YwComSjcllistForm> others=YwComSjcllistConvertor.convertOtherSjcllistFormListToSjcllistFormList(sjclList);
              sjlist.addAll(others);
              int i=1;
              for(YwComSjcllistForm sjcl:sjlist){
            	  for (YwComSjclForm tplForm : sjclTpl) {
            		  if (tplForm.getTplid() != null &&
            				  sjcl.getId().longValue() == tplForm.getTplid().longValue()) {
            			  sjcl.setSfdz("1");
            	     }
            	  }
            	  //收件材料有些只有名称
            	  if(sjcl.getFyjs()!=null && sjcl.getFyjs()>0){
            		  Long fs=sjcl.getYjs()+sjcl.getFyjs();
            		  Long fyjs=sjcl.getFyjs();
            		  String zzcl="";
            		  //if(!"0".equals(sjcl.getSfdz())){
      					zzcl="√";
      				//}
      				  variables.put("no"+i,String.valueOf(i));
   	     			  variables.put("tplname"+i,sjcl.getTitle());
   	     			  variables.put("tplname_"+i,sjcl.getTitle());
   	     			  variables.put("no_"+i,String.valueOf(i));
   	           		  variables.put("fs"+i,String.valueOf(fs));
   	           		  variables.put("zzcl"+i,String.valueOf(zzcl));
   	           		  variables.put("fyjs"+i,String.valueOf(fyjs));
   	           		  variables.put("fs_"+i,String.valueOf(fs));
   	           		  variables.put("zzcl_"+i,zzcl);
   	           		  variables.put("fyjs_"+i,String.valueOf(fyjs));
            		  i++;
            	  }
              }
              
              String area=this.ywYnJzfqwczzXnService.getArea(form.getId());
      		String gcdz=form.getGcdz();
      		String orgname="";
      		String areazfj="";
      		String areaorg="";
      		if(StringUtils.isNotBlank(area)){
      			variables.put("orgjc",area.substring(0,1));
      			orgname=area+"余泥管理所";
      			if(StringUtils.isNotBlank(gcdz)){
      				areazfj=gcdz.substring(0,3)+"城管执法局";
      				areaorg="广州市余泥渣土排放管理处办公室";
      			}
      		}else{
      			orgname="广州市余泥渣土排放管理处办公室";
      			if(StringUtils.isNotBlank(gcdz)){
      				areazfj=gcdz.substring(0,3)+"城管执法局";
      				areaorg=gcdz.substring(0,3)+"余泥管理所";
      			}
      		}
             variables.put("ysgs1", form.getYsgs());
              ServletActionContext.getRequest().setAttribute(WfConstant.PRINT_BUFFER, variables);
          }
          catch(Exception e){
              e.printStackTrace();
          }
          return WfConstant.PRINT;
    	
    }
    
    public String makeDocument() throws Exception {
        if (StringUtils.isNotBlank(form.getRedHeadFileId())) {
            String redHeadFilePath = wfBusTemplateServiceEX.getPrintTemplatePath(Long.parseLong(form.getRedHeadFileId()));
            log.info("readheadFile----->"+redHeadFilePath);
            form.setRedHeadFilePath(redHeadFilePath);
        }
         //加载收件通知书里面的附件
		 String isred=getRequest().getParameter("isred");
		 //如果不要打印红头
		 if("no".equals(isred)){
//			 String redHeadFilePath = wfBusTemplateServiceEX.getRedFile(form.getTemplateCode());
		      //form.setRedHeadFilePath("");
		 }
        String templateCode = getTemplateCode();
        if(templateCode != null && templateCode.trim().length() > 0){
            String printTemplatePath = wfBusTemplateServiceEX.getPrintTemplatePath(templateCode, WfTemplateAttachmentRefFormEX.ZHENGWEN_TEMPLATE_TYPE);
            form.setTemplatePath(printTemplatePath);
            WfTemplateAttachmentRefFormEX wfTemplateAttachmentRefFormEX = 
            	(WfTemplateAttachmentRefFormEX)wfTemplateAttachmentRefServiceEX.get(Long.parseLong(form.getZhengwenFileId()));
            String zhengwenPath = wfTemplateAttachmentRefFormEX.getFilePath() + "/" + wfTemplateAttachmentRefFormEX.getFileRealName();
            form.setZhengwenPath(zhengwenPath);
            form.setCurDate(DateUtilsEX.convertDate2Chinese(new Date()));
            form.setCurYear(String.valueOf(Calendar.getInstance().get(Calendar.YEAR)));
            Long seq=oaDocCodeServiceEX.getMaxSeqByGas(templateCode, wfTemplateAttachmentRefFormEX.getFileCode(),form.getId(),false);
	        if(seq.intValue()<10){
	        	  form.setCurSeq("0"+String.valueOf(seq));
	        }else{
	        	  form.setCurSeq(String.valueOf(seq));
	        }
	        String area=this.getLoginUser().getOrg().getOrgName();
            String qu=area.substring(0,1);
            
            Map variables=WfUtilsEX.buildMap(form, "yyyy年MM月dd日");
            variables.put("qu",qu);
            BaseAction.getRequest().setAttribute(WfConstant.PRINT_BUFFER, variables);
            getRequest().setAttribute("isunified", false);//是否全委统一
            BaseAction.getRequest().setAttribute("seq", form.getCurSeq());
            BaseAction.getRequest().setAttribute("templateFilePath",zhengwenPath);
            BaseAction.getRequest().setAttribute("fileCode", wfTemplateAttachmentRefFormEX.getFileCode());
            BaseAction.getRequest().setAttribute("entityId", form.getId());
            BaseAction.getRequest().setAttribute("templateId", wfTemplateAttachmentRefFormEX.getId());
//            BaseAction.getRequest().setAttribute("busType", OaFawen.class.getSimpleName());
        }
        return WfConstant.MAKE_DOCUMENT;
    }
    
    /**
	 * 预览复函或者处置证
	 * @return
	 */
	public String preViewFhOrCzz(){
		String templateCode = getRequest().getParameter("templateCode");
		getRequest().setAttribute("templateCode", templateCode);
		String flag = getRequest().getParameter("flag");
		String taskInstDbid = getRequest().getParameter("taskInstDbid");
		getRequest().setAttribute("taskInstDbid", taskInstDbid);
		String area=this.ywYnJzfqwczzXnService.getArea(form.getId());
		String gcdz=form.getGcdz();
		if(StringUtils.isBlank(form.getOrgFile())){
			String orgfile="市建委《关于"+form.getGcmc()+"项目列入广州市城市建设“绿色通道”的复函》（穗建开函[2011]807号）";
			form.setOrgFile(orgfile);
		}
		String orgname="";
		String areazfj="";
		String areaorg="";
		if(StringUtils.isNotBlank(area)){
			form.setZsno(area.substring(0,2));
			orgname=area+"余泥管理所";
			getRequest().setAttribute("orgjc",area.subSequence(0,2));
			if(StringUtils.isNotBlank(gcdz)){
				areazfj=gcdz.substring(0,3)+"城管执法局";
				areaorg="广州市余泥渣土排放管理处办公室";
			}
		}else{
			orgname="广州市余泥渣土排放管理处办公室";
			if(StringUtils.isNotBlank(gcdz)){
				areazfj=gcdz.substring(0,3)+"城管执法局";
				areaorg=gcdz.substring(0,3)+"余泥管理所";
			}
			form.setZsno("市处");
		}
		
		if(StringUtils.isBlank(form.getPfczl())){
			String pfczl=form.getJsztf();
			if(StringUtils.isNotBlank(pfczl)){
				try {
					pfczl=ChineseChar.changeToBig(Double.valueOf(pfczl))+"立方米";
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			form.setPfczl(pfczl);
		}
		if(StringUtils.isBlank(form.getAreaorg())){
			form.setAreaorg(areaorg);
		}
		if(StringUtils.isBlank(form.getAreazfj())){
			form.setAreazfj(areazfj);
		}
		if(StringUtils.isBlank(form.getZforg())){
			form.setZforg("市城管综合执法局执法处");
		}
		if(StringUtils.isBlank(form.getFhGd())){
			ReplyTemplate template=ywYnJzfqwczzPfsnService.getReplyTemplate("","2");
			String content=template.getContent();
			form.setFhGd(content);
		}
		 getRequest().setAttribute("orgname",orgname);
		if(StringUtils.isNotBlank(taskInstDbid)){
		  	WfBusInstanceTaskForm instance = wfService.getWfBusInstanceTaskById(Long.valueOf(taskInstDbid), this.getLoginUserName());
			String activName=instance.getActivityName();
		    getRequest().setAttribute("activName", activName);
		}else{
			 getRequest().setAttribute("activName", "");
		}
		
		if("czz".equals(flag)){
			return "preViewCzz";
		}else{
			return "preViewFh";
		}
	}
	
	/**
	 * 保存复函
	 * @return
	 * @throws IOException 
	 */
	public String saveFh() throws IOException{
        String result="true";
        try {
        	ywYnJzfqwczzXnQxService.save(form);
        } catch (Exception e) {
            result="false";
        }
        getResponse().getWriter().print(result);
	    return null;
	}
	
	/**
	 * 保存处置证
	 * @return
	 * @throws IOException 
	 */
	public String saveCzz() throws IOException{
        String result="true";
        try {
        	ywYnJzfqwczzXnQxService.save(form);
        } catch (Exception e) {
            result="false";
        }
        getResponse().getWriter().print(result);
	    return null;
	}
    
	@Override
	public String list() throws Exception {
		ywYnJzfqwczzXnQxService.search(page, form);
		return SUCCESS;
	}
	
	@Override
    public String input() throws Exception {
		  this.setOpinions();
        getRequest().setAttribute("CurrUserName", this.getLoginUser().getUser().getUserName());
        
        List<SysCodeForm> docTypeList = syscodeService.getItems("YW_QY_ZZDJ");
        getRequest().setAttribute("qyzzdj", docTypeList);
        List<SysCodeForm> gclbList = syscodeService.getItems("YW_GCLB");
        getRequest().setAttribute("gclbList", gclbList);
        return INPUT;
    }

	/**
	 * �������������޸ĵ�Form����
	 */
	@Override
	public String save() throws Exception {
		ywYnJzfqwczzXnQxService.save(form);
		return RELOAD;
	}

	/**
	 * ɾ��һ����¼
	 */
	@Override
	public String delete() throws Exception {
		ywYnJzfqwczzXnQxService.delete(id);
		return RELOAD;
	}
	
	/**
	 * ɾ�������¼
	 */
	@Override
	public String deleteMore() throws Exception{
		ywYnJzfqwczzXnQxService.delete(checkedIds);
		return RELOAD;
	}
	
	   @Override
	    protected void prepareModel() throws Exception {
		   	LoginUserForm uform=(LoginUserForm)BaseAction.getRequest().getSession().getAttribute("SES_LOGIN_USER");
			String username=uform.getUser().getUserName();
	        if(id != null){
	            form = ywYnJzfqwczzXnQxService.get(id);
	        }
	        else
	            form = new YwYnJzfqwczzXnForm();
	        
	        if (StringUtils.isBlank(form.getAcceptNo())) {
	        	String rq = DateUtilsEX.getYearAndMonthAndDay();
	        	form.setAcceptNo("gz26"+rq+"XXXXX");
	        }
	        form.setArea(uform.getOrg().getOrgName().substring(0,3));
	        if (StringUtils.isBlank(form.getSjr())) {
	            form.setSjr(this.getLoginUser().getUser().getUserName());
	        }
	        
	        if (StringUtils.isBlank(form.getCbyw())) {
	            WfBusTemplateForm wfBusTemplateForm = wfBusTemplateService.getByTemplateCode(getTemplateCode());
	            if (wfBusTemplateForm != null) {
	                form.setCbyw(wfBusTemplateForm.getTemplateName());
	            }
	        }

	        if (StringUtils.isBlank(form.getCbbm())) {
	            form.setCbbm("余泥处");
	        }

            if (form.getSarq() == null) {
                form.setSarq(new Date());
            }
            if (form.getSqDate() == null) {
                form.setSqDate(new Date());
            }
            if (form.getCpsj() == null) {
                form.setCpsj(new Date());
            }
          //答复时间
            if(id!=null && StringUtils.isNotBlank(this.getTemplateCode())){
        		Date date=this.wfServiceEX.getDfsjByTempleteCode(this.getTemplateCode(),Long.valueOf(id));
        		form.setDfsj(date);
        	}
            
            if(form.getFhYfrq() != null){
            	form.setFhYfrqStr(DateUtilsEX.convertDate2Chinese(form.getFhYfrq()));
            }
            if(StringUtils.isNotBlank(form.getGcdz())){
            	form.setGcdz2(form.getGcdz());
            }
            form.setSajg(uform.getOrg().getOrgName());
            form.setSajg2(form.getSajg());
            form.setSajg3(form.getSajg());
            form.setSajg4(form.getSajg());
            form.setSajg5(form.getSajg());
            form.setSajg6(form.getSajg());
	    }
	/**
	 * ׼��ҳ��ģ��
	 */

	public YwYnJzfqwczzXnForm getModel() {
		return form;
	}
	
	// ����getter��setter����
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long[] getCheckedIds() {
		return checkedIds;
	}

	public void setCheckedIds(Long[] checkedIds) {
		this.checkedIds = checkedIds;
	}
	
	public Page<YwYnJzfqwczzXnForm> getPage() {
		return page;
	}


	public void setPage(Page<YwYnJzfqwczzXnForm> page) {
		this.page = page;
	}
}
